package zero.tech.games.log.shareding;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import com.google.common.collect.Lists;
import com.google.common.collect.Range;

//PreciseShardingAlgorithm
//RangeShardingAlgorithm
//ComplexKeysShardingAlgorithm 
public class TimeShardingAlgorithm implements PreciseShardingAlgorithm<Date>,RangeShardingAlgorithm<Date>{
	@Override
	public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {
		String tb_name = shardingValue.getLogicTableName();
		Date date = shardingValue.getValue();
		String year = String.format("%tY", date);
        String mon =String.valueOf(Integer.parseInt(String.format("%tm", date))); // 去掉前缀0
//        String dat = String.format("%td", date);
        String tb_name_choose=tb_name+"_"+year+"_"+mon;
		if(availableTargetNames.contains(tb_name_choose)) {
			return tb_name_choose;
		}
		throw new IllegalArgumentException();
	}

	@Override
	public Collection<String> doSharding(Collection<String> availableTargetNames,
			RangeShardingValue<Date> shardingValue) {
		List<String> list=new ArrayList<String>();
		String tb_name = shardingValue.getLogicTableName();
		Range<Date>range=shardingValue.getValueRange();
		Date lowerEnd =range.lowerEndpoint();
		Date upperEnd =range.upperEndpoint();
		if (lowerEnd != null && upperEnd != null) {
			List<String> rangeNameList = getRangeNameList(tb_name,lowerEnd, upperEnd);
			for (String name : rangeNameList) {
				if(availableTargetNames.contains(name)) {
					list.add(name);
				}
			}
		}
		return list;
	}
	
	private static List<String> getRangeNameList(String logicName,Date start, Date end) {
		List<String> result = Lists.newArrayList();
		Calendar dd = Calendar.getInstance();// 定义日期实例
		dd.setTime(end);// 设置日期起始时间
		while (dd.getTime().after(start)) {// 判断是否到结束日期
			String year = String.format("%tY", dd);
	        String mon =String.valueOf(Integer.parseInt(String.format("%tm", dd))); // 去掉前缀0
			result.add(logicName+"_"+year+"_"+mon);
			dd.add(Calendar.MONTH, -1);// 进行当前日期月份加1
		}
		return result;
	}


}
